package com.example.tliasmanagement.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@RequestMapping("/cookie")
@RestController
public class CookieController {


    @GetMapping("/login")
    public String login(HttpServletResponse response){
        // 用户名 密码校验
        // 生成cookie
        Cookie idCookie = new Cookie("userId", "1");
        Cookie nameCookie = new Cookie("username", "zhangsan");
        response.addCookie(idCookie);
        response.addCookie(nameCookie);
        return "success";
    }

    /**
     * 获取用户的订单列表
     * */
    @GetMapping("orders")
    public String orders(HttpServletRequest request){
        Integer userId = 0;
        String username = "";
        // 获取当前登录的用户
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            String value = cookie.getValue();
            if(Objects.equals(name, "userId")){
                userId = Integer.parseInt(value);
            }
            if(Objects.equals(name, "username")){
                username = value;
            }
        }
        // 根据用户id查询订单列表
        // select * from order where userId= #{userId}
        return userId + ":" + username + ":order list" ;
    }

}